import datetime

from django.views import View
from django.db import transaction

from User.models import OrderYard
from Venue.models import VenueSportYard
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequiredUser


class YardView(LoginRequiredUser, View):
    """ 订场订单 """

    @Req.getJson
    def post(self, request):
        """ 添加 """
        yardId = request.json_dict.get('yardId')
        index = request.json_dict.get('index')
        timeId = request.json_dict.get('timeId')
        number = request.json_dict.get('number')
        message = request.json_dict.get('message')

        user = request.user.user

        with transaction.atomic():
            yard = VenueSportYard.objects.select_for_update().filter(id=yardId).first()
            if not yard:
                return Res.Json(Res.ParamErr)
            time = yard.getTime(index, timeId)
            if not time:
                return Res.Json(Res.ParamErr)

            # 判断时间
            date = datetime.date.today() + datetime.timedelta(days=index)
            dt = datetime.datetime.strptime(f"{date} {time.startTime}", "%Y-%m-%d %H:%M")
            if index == 0 and dt <= datetime.datetime.now():
                return Res.Json(Res.Warn, msg='时间已过')
            if time.reserved < number:
                return Res.Json(Res.Warn, msg='容量不足', reserved=time.reserved)
            order = OrderYard.create(user, yard, date, time, number=number, message=message)

            return Res.Json(Res.OK, result=order.Info())
